<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button @click="ADDdialogVisible = true" type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
    <el-table border stripe :data="RoleLists">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :class="['bdbottom',i1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1,i1) in scope.row.rights" :key="item1._id">
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag @close="removeRightById()" closable>{{ item1.rightName }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级权限 -->
            <el-col :span="19">
              <el-row :class="[i2 === 0 ? '' : 'bdtop','vcenter']" v-for="(item2,i2) in item1.secondRights" :key="item2._id">
                  <el-col :span="6">
                      <el-tag type="success" @close="removeRightById()" closable>{{item2.secondName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" @close="removeRightById(scope.row, item3._id)" closable v-for="(item3) in item2.threeRights" :key="item3._id">{{item3.threeName}}</el-tag>
                  </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
       <el-table-column label="操作" >
          <template slot-scope="scope">
            <el-button v-model="scope.row.id" type="primary" icon="el-icon-edit" size="mini" @click="editFormInfo(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removePowerById">删除</el-button>
            <el-button type="warning" @click="showRightBox(scope.row)" icon="el-icon-setting" size="mini">分配权限</el-button>
          </template>
        </el-table-column>
    </el-table>
    </el-card>
    <!-- 权限分配弹窗 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightDialogVisible"
      width="40%"
      @close="clearRightState"
      >
      <!-- 树形控件 -->
      <el-tree :data="getRightList" :props="rightProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultCheckList" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancenlGivePower">取 消</el-button>
        <el-button type="primary" @click="saveGetPowerState">确 定</el-button>
     </span>
    </el-dialog>
    <!-- 添加角色 -->
        <el-dialog
          title="添加角色"
          :visible.sync="ADDdialogVisible"
           width="40%"
           @close="clearAddInfo">
           <!-- 添加信息 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <!-- 底部按钮 -->
          <span slot="footer" class="dialog-footer">
          <el-button @click="ADDdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUsers">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改角色信息 -->
         <el-dialog
          title="修改角色"
          :visible.sync="editdialogVisible"
           width="40%"
           @close="editFormClose"
           >
           <!-- 修改信息 -->

          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="editForm.roleName" ></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc" type="password">
              <el-input v-model="editForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>

          <!-- 底部按钮 -->
          <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editPreVaildate">确 定</el-button>
          </span>
        </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      RoleLists: [],
      rightDialogVisible: false,
      getRightList: [],
      // 树形控件
      rightProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中值
      defaultCheckList: [],
      // 添加角色按钮
      ADDdialogVisible: false,
      // 添加表单
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      editForm: {},
      editdialogVisible: false,
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      deleteRight: {
        roleId: '',
        rightId: ''
      },
      roleId: ''
    }
  },
  created () {
    this.getRoleLists()
  },
  methods: {
    async getRoleLists () {
      const res = await this.$http.get('/roleList')
      this.RoleLists = res.data
    },
    // 根据ID删除权限
    async removeRightById (role, right) {
      // 弹出提示框
      this.deleteRight.roleId = role._id
      this.deleteRight.rightId = right
      const result = await this.$confirm('此操作将永久该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消该操作')
      }
      await this.$http.delete('/dtThree', { params: this.deleteRight })
      this.$message.success('删除成功！')
      console.log(role._id)
      console.log(right)
      this.getRoleLists()
    },
    // 获取全部权限列表数据
    async showRightBox (role) {
      this.rightDialogVisible = true
      const res = await this.$http.get('/right')
      this.roleId = role._id
      this.getRightByRole(role, this.defaultCheckList)
      this.getRightList = res.data.lise
    },
    // 获得当前角色所有权限并保存在defaultCheckList中
    getRightByRole (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getRightByRole(item, arr)
      })
    },
    clearRightState () {
      this.defaultCheckList = []
    },
    cancenlGivePower () {
      this.rightDialogVisible = false
      this.$message.info('改操作已取消')
    },
    async saveGetPowerState () {
      this.rightDialogVisible = false
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys()
      ]
      await this.$http.post('/dispeach', { right: keys, roleId: this.roleId })
      console.log(keys)
      console.log(this.roleId)
      this.$message.success('权限分配成功!')
    },
    // 删除角色
    async removePowerById () {
      // 弹出提示框
      const result = await this.$confirm('此操作将永久该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消该操作')
      }
      this.$message.success('删除成功！')
    },
    clearAddInfo () {
      this.$refs.addFormRef.resetFields()
    },
    addUsers () {
      this.$message.success('添加成功！')
      this.ADDdialogVisible = false
    },
    editFormInfo (data) {
      this.editForm = data
      this.editdialogVisible = true
    },
    editPreVaildate () {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return this.$message.error('请输入合法字符！')
        this.editdialogVisible = false
        this.$message.success('修改信息成功！')
      })
    },
    editFormClose () {
      this.$refs.editFormRef.resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin:7px;
}

.bdtop {
  border-top : 1px solid #eee;
}

.bdbottom {
  border-bottom : 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
